package org.budo.support.velocity.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class VelocityUtil {
    @SuppressWarnings("deprecation")
    public static String mergeTemplateIntoString(VelocityEngine velocityEngine, String templateLocation, String encoding, Map<String, Object> model) {
        return org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, encoding, model);
    }

    public static Map<String, Object> contextToMap(Context context) {
        if (null == context) {
            log.error("#22 contextToMap, context = " + context);
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Object[] keys = context.getKeys();
        if (null == keys || keys.length < 1) {
            return map;
        }

        for (Object key : keys) {
            if (null == key) {
                log.warn("#36 contextToMap, key is null, context = " + context);
                continue;
            }

            if ("org.springframework.web.servlet.DispatcherServlet.CONTEXT".equalsIgnoreCase(key.toString()) //
                    || "org.springframework.web.servlet.DispatcherServlet.THEME_SOURCE".equalsIgnoreCase(key.toString()) //
                    || "springMacroRequestContext".equalsIgnoreCase(key.toString()) //
                    || "rc".equalsIgnoreCase(key.toString()) //
                    || key.toString().startsWith("org.springframework.validation.BindingResult.")) {
                continue;
            }

            Object value = context.get(key.toString());
            if (null == value) {
                log.debug("#44 contextToMap, value is null, key = {}, context = {}", key, context);
                continue;
            }

            map.put(key.toString(), value);
        }

        return map;
    }
}